package services;

import java.util.Date;
import java.util.List;

import models.Resource;
import models.ResourceHierarchy;
import models.ResourceHierarchyPK;
import models.ResourceType;

public class TestCaseService extends ResourceService {
	
	private static final String RESOURCES_DIRECTORY = "resources/testcases/";
	
	private static TestCaseService service;
	
	// Singleton pattern
	private TestCaseService() {
	}
	
	public static TestCaseService getService() {
		if (service == null) {
			service = new TestCaseService();
		}
		return service;
	}
	
	public List<Resource> getAllTestCases(long testSuiteId) {
		return getChildResources(testSuiteId, ResourceType.TestCase);
	}
	
	public Resource getTestCase(long testCaseId) {
		return Resource.find.byId(testCaseId);
	}
	
	public void saveTestCase(long testSuiteId, Resource testCase) {
		if (testCase.getId() <= 0) {
			createTestCase(testSuiteId, testCase);
		} else {
			updateTestCase(testCase);
		}
	}
	
	private void createTestCase(long testSuiteId, Resource testCase) {
		Date currentDate = new Date();
		testCase.setType(ResourceType.TestCase);
		testCase.setCreateDate(currentDate);
		testCase.setLastModified(currentDate);
		testCase.save();
		testCase.setResourcePath(RESOURCES_DIRECTORY + testCase.getId());
		testCase.save();
		
		ResourceHierarchyPK pk = new ResourceHierarchyPK();
		pk.setParentId(testSuiteId);
		pk.setChildId(testCase.getId());
		ResourceHierarchy rh = new ResourceHierarchy(pk);
		rh.save();
	}
	
	private void updateTestCase(Resource testCase) {
		testCase.setLastModified(new Date());
		testCase.save();
	}
	
}
